package com.jader.activities;
/*购物车*/
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ExpandableListView.OnGroupClickListener;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jader.adapter.ShopCartAdapter;
import com.jader.adapter.ShopCartAdapter.OnShopCartChildClickListener;
import com.jader.beans.Address;
import com.jader.beans.ShopCartGoods;
import com.jader.myviews.DeleteShopcartAlertDialog;
import com.jader.myviews.MyProgressDialog;
import com.jader.myviews.ShopcatPopWindow;
import com.jader.util.JaderApplication;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

public class ShopCartActivity extends Activity implements
		OnShopCartChildClickListener {
	TextView shopcart_title, tv_shopcart_finalCount;
	Button btn_shopcart_pay;
	CheckBox CB_shopcart_bottom;
	ImageView shopcart_back;
	ExpandableListView shopCartListView;
	private ShopcatPopWindow popWindow;
	private HttpUtils httpUtils;
	ShopCartAdapter cartAdapter;
	private View yingyin_two;
	private Map<Integer, ShopCartGoods> pay_now;
	private String url = JaderApplication.getIP() + "/Jader/client";
	List<ShopCartGoods> cartList = new ArrayList<ShopCartGoods>(0);
	List<String> sellerName = new ArrayList<String>(0);
	Map<String, List<ShopCartGoods>> goodMap = new HashMap<String, List<ShopCartGoods>>();
	private OnCheckAllListener onCheckAllListener;
	private int shopcart_requestcode = 2;
	private List<ShopCartGoods> list = new ArrayList<ShopCartGoods>(0);
	private MyProgressDialog dialog;
	private DeleteShopcartAlertDialog deleteShopcartAlertDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shop_cart);
		initView();
		sendRequest();
	}

	private void sendRequest() {
		String url = JaderApplication.getIP() + "/Jader/client";
		RequestParams params = new RequestParams();
		params.addBodyParameter("type", "" + JaderApplication.SHOPCART_SELECT);
		params.addBodyParameter("userid", JaderApplication.user.getUserid()
				+ "");
		httpUtils = new HttpUtils();
		dialog = JaderApplication.getMyDialog(this);
		dialog.show();
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						JaderApplication.show(getBaseContext(), "请求超时");
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						String result = info.result;
						Log.e("cartList", result);
						// 把json字符串转换为javabean对象
						Gson gson = new Gson();
						Type typeofType = new TypeToken<List<ShopCartGoods>>() {
						}.getType();
						List<ShopCartGoods> list = gson.fromJson(result,
								typeofType);
						cartList.addAll(list);
						for (int i = 0; i < cartList.size(); i++) {
							goodMap.put(cartList.get(i).getSeller()
									.getSellername(), null);
						}
						Set<Entry<String, List<ShopCartGoods>>> set = goodMap
								.entrySet();
						Iterator<Entry<String, List<ShopCartGoods>>> iterator = set
								.iterator();
						while (iterator.hasNext()) {
							Entry<String, List<ShopCartGoods>> entry = iterator
									.next();
							sellerName.add(entry.getKey());
						}
						for (int i = 0; i < sellerName.size(); i++) {
							List<ShopCartGoods> goodsList = new ArrayList<ShopCartGoods>();
							for (int j = 0; j < cartList.size(); j++) {
								if (sellerName.get(i).equals(
										cartList.get(j).getSeller()
												.getSellername())) {
									goodsList.add(cartList.get(j));
								}
							}
							goodMap.put(sellerName.get(i), goodsList);
							cartAdapter.notifyDataSetChanged();
							Log.e("zhuyaxing",
									"" + cartAdapter.getChildrenCount(0));
						}
						for (int i = 0; sellerName != null
								&& i < sellerName.size(); i++) {
							shopCartListView.expandGroup(i);
						}
						if (dialog.isShowing()) {
							dialog.dismiss();
						}
					}
				});
	}

	private void initView() {
		pay_now = new HashMap<Integer, ShopCartGoods>();
		deleteShopcartAlertDialog = new DeleteShopcartAlertDialog(this)
				.builder();
		deleteShopcartAlertDialog.setTitle("确认要删除该商品吗？");
		deleteShopcartAlertDialog.setNegativeButton("取消", null);

		shopcart_title = (TextView) findViewById(R.id.top_actiobar_text);
		shopcart_title.setText("购物车");
		shopcart_back = (ImageView) findViewById(R.id.top_actionbar_back);
		shopCartListView = (ExpandableListView) findViewById(R.id.ShopCart_ListView);
		
		CB_shopcart_bottom = (CheckBox) findViewById(R.id.checkbox_shopcart_goodAllCheck);
		btn_shopcart_pay = (Button) findViewById(R.id.btn_shopcart_buy_all);
		tv_shopcart_finalCount = (TextView) findViewById(R.id.tv_shopcart_count);
		// 去掉箭头
		shopCartListView.setGroupIndicator(null);
		// 不收缩
		shopCartListView.setOnGroupClickListener(new OnGroupClickListener() {
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				return true;
			}
		});
		CB_shopcart_bottom
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton arg0,
							boolean arg1) {
						onCheckAllListener.onCheckAllListener(arg1);

					}
				});
		cartAdapter = new ShopCartAdapter(sellerName, goodMap,
				ShopCartActivity.this);
		cartAdapter.setOnShopCartChildClickListener(this);
		shopCartListView.setAdapter(cartAdapter);
		popWindow = new ShopcatPopWindow(this);
		yingyin_two = findViewById(R.id.yingyin_three);
		popWindow
				.setOnItemClickListener(new ShopcatPopWindow.OnItemClickListener() {

					@Override
					public void onClickOKPop() {
						setBackgroundBlack(yingyin_two, 1);

					}
				});
		btn_shopcart_pay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(ShopCartActivity.this,
						AddressChoice.class);
				if (JaderApplication.isEmpty(tv_shopcart_finalCount.getText()
						.toString().trim())) {
					JaderApplication.show(ShopCartActivity.this, "您还没有选择商品哟");
				} else {
					list = new ArrayList<ShopCartGoods>(0);
					Collection<ShopCartGoods> c = pay_now.values();
					Iterator<ShopCartGoods> iterator = c.iterator();
					while (iterator.hasNext()) {
						list.add(iterator.next());
					}
					if (list.size() > 0) {
						intent.putExtra("userid", list.get(0).getShopcart()
								.getUserid());
						Log.e("user", list.get(0).getShopcart().getUserid()
								+ "");
						startActivityForResult(intent, shopcart_requestcode);
					}
				}
			}
		});
		shopcart_title.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				ShopCartActivity.this.finish();

			}
		});
		shopCartListView
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> arg0,
							View arg1, int arg2, long arg3) {
						final int groupPos = (Integer) arg1
								.getTag(R.id.tv_parent_sellername); // 参数值是在setTag时使用的对应资源id号
						final int childPos = (Integer) arg1
								.getTag(R.id.tv_child_goodname);
						if (childPos == -1) {// 长按的是父项
							// 根据groupPos判断你长按的是哪个父项，做相应处理（弹框等）
							Log.v("longgroup", sellerName.get(groupPos));
						} else {
							// 根据groupPos及childPos判断你长按的是哪个父项下的哪个子项，然后做相应处理。
							Log.v("longchild",
									goodMap.get(sellerName.get(groupPos))
											.get(childPos).toString());
							deleteShopcartAlertDialog.setPositiveButton("确认",
									new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											delete(goodMap
													.get(sellerName
															.get(groupPos))
													.get(childPos)
													.getShopcart()
													.getShopcartid(), childPos,
													groupPos);

										}
									});
							deleteShopcartAlertDialog.show();
						}

						return true;
					}
				});
		shopCartListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView arg0, View arg1,
					int arg2, int arg3, long arg4) {
				Intent intent = new Intent(ShopCartActivity.this, Seller.class);
				intent.putExtra("goods",
						goodMap.get(sellerName.get(arg2)).get(arg3).getGoods());
				startActivity(intent);
				return false;
			}
		});
		
		shopcart_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	public void setBackgroundBlack(View view, int what) {
		switch (what) {
		case 0:
			view.setVisibility(View.VISIBLE);
			break;
		case 1:
			view.setVisibility(View.GONE);
			break;
		}
	}

	@Override
	public void onShopCartChildClickListener(ShopCartGoods shopCartGoods,
			boolean isChecked) {
		double money = 0;
		int number = 0;
		if (isChecked) {
			pay_now.put(shopCartGoods.getShopcart().getShopcartid(),
					shopCartGoods);
		} else {
			pay_now.remove(shopCartGoods.getShopcart().getShopcartid());
		}
		Set<Entry<Integer, ShopCartGoods>> set = pay_now.entrySet();
		Iterator<Entry<Integer, ShopCartGoods>> iterator = set.iterator();
		while (iterator.hasNext()) {
			Entry<Integer, ShopCartGoods> entry = iterator.next();
			ShopCartGoods s = entry.getValue();
			money = money + s.getGoods().getPrice()
					* s.getShopcart().getNumber();
			number = number + s.getShopcart().getNumber();

		}
		btn_shopcart_pay.setText("结算(" + number + ")");
		tv_shopcart_finalCount.setText(JaderApplication.getPrice(money));
	}

	public interface OnCheckAllListener {
		void onCheckAllListener(boolean isChecked);
	}

	public void setOnCheckAllListener(OnCheckAllListener onCheckAllListener) {
		this.onCheckAllListener = onCheckAllListener;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == shopcart_requestcode) {
			Address address = (Address) data.getSerializableExtra("address");
			popWindow.payment(list, address.getAddressid());
			setBackgroundBlack(yingyin_two, 0);
			popWindow.showAsDropDown(btn_shopcart_pay);
		}
	}

	public void delete(int shopcartid, final int childPosition,
			final int parentPosition) {
		dialog.show();
		RequestParams params = new RequestParams();
		params.addBodyParameter("type", JaderApplication.DELETE_SHOP_CART_GOODS
				+ "");
		params.addBodyParameter("shopcartid", shopcartid + "");
		JaderApplication.httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						if (dialog.isShowing()) {
							dialog.dismiss();
						}

					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						if ("true".equals(arg0.result)) {
							goodMap.get(sellerName.get(parentPosition)).remove(
									childPosition);
							cartAdapter.notifyDataSetChanged();
							JaderApplication
									.show(ShopCartActivity.this, "删除成功");
						}
						if (dialog.isShowing()) {
							dialog.dismiss();
						}

					}
				});

	}

}
